package com.example.security;

import com.example.utils.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

/**
 * 用户
 */
public class SecurityUser {
    /**
     * 获取用户信息
     */
    public static InfoDetail getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication.getPrincipal() == "anonymousUser") {
            return null;
        }
        JwtAuthenticationToken token = (JwtAuthenticationToken) authentication;
        Object o = token.getTokenAttributes().get("infoDetail");
        return JSON.convert(o, InfoDetail.class);
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        if (getUser() == null) {
            return null;
        }
        return getUser().getId();
    }

    /**
     * 获取部门ID
     */
    public static Long getDeptId() {
        if (getUser() == null) {
            return null;
        }

        return getUser().getDeptId();
    }
    public static Long getTenantId() {
        if (getUser() == null) {
            return null;
        }

        return getUser().getTenantId();
    }
    public static Long getStoreId() {
        if (getUser() == null) {
            return null;
        }

        return getUser().getStoreId();
    }
    public static String getUserName() {
        if (getUser() == null) {
            return null;
        }

        return getUser().getUsername();
    }
}